<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px;" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="资源名" prop="Q_name_S_LK">
            <el-input v-model="queryData.Q_name_S_LK" placeholder="资源名"/>
          </el-form-item>
          <el-form-item label="资源类别" prop="Q_type_S_EQ">
            <el-select v-model="queryData.Q_type_S_EQ" placeholder="资源类别">
              <el-option label="全部" value=""/>
              <el-option
                v-for="item in optionOfTypes"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['training:resource:edit']" size="mini" plain type="primary" icon="el-icon-plus" @click="handleEdit()">
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['training:resource:delete']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData"/>
        </el-row>
        <el-table
          ref="resource_table"
          v-loading="tableLoading"
          row-key="resourceId"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40"/>
          <el-table-column align="center" label="资源类型" prop="extension" width="90">
            <template slot-scope="scope">
              <el-tooltip :content="getDictValue('type', scope.row.type)" placement="right">
                <img :src="setFileImg(scope.row.extension)" style="width: 30px;">
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="名称" prop="name" show-overflow-tooltip>
            <template slot-scope="scope">
              <span style="cursor: pointer" @click="handleEdit(scope.row.resourceId)">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="资源大小" prop="size" width="110" show-overflow-tooltip>
            <template slot-scope="scope">
              <div style="padding: 0 10px;">{{ calculateFileSize(scope.row.size) }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="视频时长" prop="size" width="110" show-overflow-tooltip>
            <template slot-scope="scope">
              <div style="padding: 0 10px;">{{ calculateVideoTime(scope.row.duration) }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" sortable width="150" prop="createTime" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.createTime | parseTime('{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="190" fixed="right">
            <template slot-scope="scope">
              <el-link class="m-r-10" type="primary" icon="el-icon-view" @click="handleInfo(scope.row.name, scope.row.type, scope.row.fileId)">预览</el-link>
              <el-dropdown>
                <span class="el-dropdown-link" style="font-size: smaller">
                  更多<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permission="['training:resource:edit']">
                    <el-link type="primary" icon="el-icon-files" @click="handleEdit(scope.row.resourceId)">编辑</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['training:resource:delete']">
                    <el-link type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.resourceId)">删除</el-link>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData"/>
      </el-card>
    </el-row>

    <training-resource-view v-if="openViewDialog" ref="view_dialog" />
    <training-resource-form-dialog v-if="openFormDialog" ref="form_dialog" @confirmForm="handleFilter"/>
  </div>
</template>

<script>
import { resourceTable, resourceDelete } from '@/api/training/resource'
import { convertTimeMs } from '@/utils'
import TrainingResourceView from './view'
import TrainingResourceFormDialog from './form/dialog'

export default {
  components: { TrainingResourceView, TrainingResourceFormDialog },
  data() {
    return {
      //  可以识别的文件类型
      fileImgTypeList: [
        'png',
        'jpg',
        'jpeg',
        'docx',
        'doc',
        'ppt',
        'pptx',
        'xls',
        'xlsx',
        'avi',
        'mp4',
        'css',
        'csv',
        'chm',
        'rar',
        'zip',
        'dmg',
        'mp3',
        'open',
        'pdf',
        'rtf',
        'txt',
        'oa',
        'js',
        'html',
        'img',
        'sql',
        'jar',
        'svg',
        'gif',
        'json',
        'exe'
      ],
      //  文件图片Map映射
      fileImgMap: {
        dir: require('@/assets/images/file/dir.png'),
        chm: require('@/assets/images/file/file_chm.png'),
        css: require('@/assets/images/file/file_css.png'),
        csv: require('@/assets/images/file/file_csv.png'),
        png: require('@/assets/images/file/file_pic.png'),
        jpg: require('@/assets/images/file/file_pic.png'),
        jpeg: require('@/assets/images/file/file_pic.png'),
        docx: require('@/assets/images/file/file_word.png'),
        doc: require('@/assets/images/file/file_word.png'),
        ppt: require('@/assets/images/file/file_ppt.png'),
        pptx: require('@/assets/images/file/file_ppt.png'),
        xls: require('@/assets/images/file/file_excel.png'),
        xlsx: require('@/assets/images/file/file_excel.png'),
        mp4: require('@/assets/images/file/file_video.png'),
        avi: require('@/assets/images/file/file_avi.png'),
        rar: require('@/assets/images/file/file_rar.png'),
        zip: require('@/assets/images/file/file_zip.png'),
        dmg: require('@/assets/images/file/file_dmg.png'),
        mp3: require('@/assets/images/file/file_music.png'),
        open: require('@/assets/images/file/file_open.png'),
        pdf: require('@/assets/images/file/file_pdf.png'),
        rtf: require('@/assets/images/file/file_rtf.png'),
        txt: require('@/assets/images/file/file_txt.png'),
        oa: require('@/assets/images/file/file_oa.png'),
        js: require('@/assets/images/file/file_js.png'),
        html: require('@/assets/images/file/file_html.png'),
        img: require('@/assets/images/file/file_img.png'),
        sql: require('@/assets/images/file/file_sql.png'),
        jar: require('@/assets/images/file/file_jar.png'),
        svg: require('@/assets/images/file/file_svg.png'),
        gif: require('@/assets/images/file/file_gif.png'),
        json: require('@/assets/images/file/file_json.png'),
        exe: require('@/assets/images/file/file_exe.png'),
        unknown: require('@/assets/images/file/file_unknown.png')
      },
      showSearch: true,
      queryData: {
        Q_name_S_LK: undefined,
        Q_type_S_EQ: undefined,
        Q_status_S_EQ: '0'
      },
      tableData: [],
      tableLoading: false,
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: [],
      optionOfTypes: [],
      openViewDialog: false,
      openFormDialog: false
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 加载下拉菜单
      this.getDictData()
      this.getTableData()
    },
    getDictData() {
      this.$dictGroup('sys_file_type').then(response => {
        this.optionOfTypes = response
      }).catch(e => {})
    },
    getDictType(field, value) {
      return this.$api.getDictElement(this.optionOfTypes, value + '')[0]
    },
    getDictValue(field, value) {
      return this.$api.getDictElement(this.optionOfTypes, value + '')[1]
    },
    getDictColor(field, value) {
      return this.$api.getDictElement(this.optionOfTypes, value + '')[2]
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      resourceTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.resource_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    // 根据文件扩展名设置文件图片
    setFileImg(extendName) {
      if (extendName === null) {
        // 文件夹
        return this.fileImgMap.dir
      } else if (!this.fileImgTypeList.includes(extendName)) {
        // 无法识别文件类型的文件
        return this.fileImgMap.unknown
      } else {
        // 可以识别文件类型的文件
        return this.fileImgMap[extendName]
      }
    },
    // 计算文件大小
    calculateFileSize(size) {
      const B = 1024
      const KB = Math.pow(1024, 2)
      const MB = Math.pow(1024, 3)
      const GB = Math.pow(1024, 4)
      if (!size) {
        return '_'
      } else if (size < KB) {
        return (size / B).toFixed(0) + 'KB'
      } else if (size < MB) {
        return (size / KB).toFixed(1) + 'MB'
      } else if (size < GB) {
        return (size / MB).toFixed(2) + 'GB'
      } else {
        return (size / GB).toFixed(3) + 'TB'
      }
    },
    // 计算视频时长
    calculateVideoTime(duration) {
      return convertTimeMs(duration * 1000)
    },
    sortChange(data) {
      const {prop, order} = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleInfo(name, type, fileId) {
      this.openViewDialog = true
      this.$nextTick(() => {
        this.$refs.view_dialog.init(name, type, fileId)
      })
    },
    handleEdit(id) {
      this.openFormDialog = true
      this.$nextTick(() => {
        this.$refs.form_dialog.init(id)
      })
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function (trainingResource, index) {
        return trainingResource.resourceId
      }).join(',')

      id = id || ids
      if (!id || id.length === 0) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        resourceDelete({ids: id}).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {
        })
      }).catch(e => {
      })
    }
  }
}
</script>
